package com.xiaoyi.utils;


import com.xiaoyi.httplibrary.ProgressHelper;
import com.xiaoyi.httplibrary.ProgressListener;
import okhttp3.*;

import javax.net.ssl.*;
import java.io.*;
import java.net.FileNameMap;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URLConnection;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by 周旭 on 2017/1/18.
 * OKHttp工具类(上传，下载文件)
 */

public class OKHttpPan {
    /**
     * 生成安全套接字工厂，用于https请求的证书跳过
     * @return
     */
    public  SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());
            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }
        return ssfFactory;
    }
    /**
     * 用于信任所有证书
     */
     class TrustAllCerts implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        }
        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

        }
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }
    private  OkHttpClient client;


    public OKHttpPan() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                //设置连接超时等属性,不设置可能会报异常
                .connectTimeout(120, TimeUnit.SECONDS)
                .readTimeout(120, TimeUnit.SECONDS)
                .writeTimeout(120, TimeUnit.SECONDS);
        //设置代理,需要替换

            /*Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("61.135.217.7", 80));
            builder.proxy(proxy);*/

        builder.sslSocketFactory(createSSLSocketFactory(),new TrustAllCerts());
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        client = builder.build();
    }

    public OKHttpPan(String pxIp,int pxPort) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                //设置连接超时等属性,不设置可能会报异常
                .connectTimeout(120, TimeUnit.SECONDS)
                .readTimeout(120, TimeUnit.SECONDS)
                .writeTimeout(120, TimeUnit.SECONDS);
        //设置代理,需要替换
            System.out.println("代理ip"+pxIp+":"+pxPort);
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(pxIp, pxPort));
            builder.proxy(proxy);

        builder.sslSocketFactory(createSSLSocketFactory(),new TrustAllCerts());
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        client = builder.build();
    }
    /**
     * get 请求
     * @param url
     * @param params
     */
    public  String doGet(String url, HashMap<String, String> params, HashMap<String, String> header) {
        Request.Builder builder = new Request.Builder();
        if(null!=header){
            for (String key : header.keySet()) {
                builder.header(key, header.get(key));
            }
        }
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
        if(null!=params){
            for (String key : params.keySet()) {
                urlBuilder.addQueryParameter(key, params.get(key));
            }
        }
        Request request = builder.url(urlBuilder.build()).build();
        Call call = client.newCall(request);
        Response response = null;
        String resData = "";
        try {
            response = call.execute();
        }catch (IOException e){
            resData = "";
        }
        if(null!=response){
            try {
                resData = response.body().string();
            } catch (IOException e) {
                resData = "";
            }
        }
        return resData;
    }

    /**
     * get 请求
     * @param url
     * @param params
     */
    public  String doGet(String url, HashMap<String, String> params) {
        Request.Builder builder = new Request.Builder();
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
        if(null!=params){
            for (String key : params.keySet()) {
                urlBuilder.addQueryParameter(key, params.get(key));
            }
        }
        Request request = builder.url(urlBuilder.build()).build();
        Call call = client.newCall(request);
        Response response = null;
        String resData = "";
        try {
            response = call.execute();
        }catch (IOException e){
            resData = "";
        }
        if(null!=response){
            try {
                resData = response.body().string();
            } catch (IOException e) {
                resData = "";
            }
        }
        return resData;
    }

    public  void doAsyGet(String url,HashMap<String,String> params,Callback callback){
        Request.Builder builder1 = new Request.Builder();
        HttpUrl.Builder urlBuilder1 = HttpUrl.parse(url).newBuilder();
        if(null!=params){
            for (String key : params.keySet()) {
                urlBuilder1.addQueryParameter(key, params.get(key));
            }
        }
        Request request1 = builder1.url(urlBuilder1.build()).build();
        Call call = client.newCall(request1);
        call.enqueue(callback);
    }

    /**
     * 获取文件MimeType
     *
     * @param filename 文件名
     * @return
     */
    private  String getMimeType(String filename) {
        FileNameMap filenameMap = URLConnection.getFileNameMap();
        String contentType = filenameMap.getContentTypeFor(filename);
        if (contentType == null) {
            contentType = "application/octet-stream"; //* exe,所有的可执行程序
        }
        return contentType;
    }

    /**
     * 上传文件
     * 获得Request实例(不带进度)
     *
     * @param url       上传文件到服务器的地址
     * @param fileNames 完整的文件名（带完整路径）
     * @return
     */
    private  Request getRequest(String url, List<String> fileNames) {
        Request.Builder builder = new Request.Builder();
        builder.url(url)
                .post(getRequestBody(fileNames))
                .tag(url) //设置请求的标记，可在取消时使用
        ;
        return builder.build();
    }

    /**
     * 上传文件
     * 获得Request实例(带进度)
     *
     * @param url                       上传文件到服务器的地址
     * @param fileNames                 完整的文件名（带完整路径）
     * @param uiProgressRequestListener 上传进度的监听器
     * @return
     */
    private  Request getRequest(String url, List<String> fileNames, ProgressListener uiProgressRequestListener) {
        Request.Builder builder = new Request.Builder();
        builder.url(url)
                .post(ProgressHelper.addProgressRequestListener(
                        getRequestBody(fileNames),
                        uiProgressRequestListener));
        return builder.build();
    }

    /**
     * 通过Url地址和表单的键值对来创建Request实例
     *
     * @param url 上传表单数据到服务器的地址
     * @param map 由提交的表单的每一项组成的HashMap
     *            （如用户名，key:username,value:zhangsan）
     * @return
     */
    private  Request getRequest(String url, HashMap<String, String> map) {
        Request.Builder builder = new Request.Builder();
        builder.url(url)
                .post(getRequestBody(map))
                .tag(url) //设置请求的标记，可在取消时使用
        ;
        return builder.build();
    }

    /**
     * 通过Url地址和表单的键值对来创建Request实例
     *
     * @param url       上传表单数据到服务器的地址
     * @param map       由提交的表单的每一项组成的HashMap
     *                  （如用户名，key:username,value:zhangsan）
     * @param fileNames 完整的文件路径名
     * @return
     */
    private  Request getRequest(String url, HashMap<String, String> map, List<String> fileNames) {
        Request.Builder builder = new Request.Builder();
        builder.url(url)
                .post(getRequestBody(map, fileNames))
                .tag(url) //设置请求的标记，可在取消时使用
        ;
        return builder.build();
    }

    /**
     * 通过下载的URL地址构建request实例
     *
     * @param downloadUrl 文件下载的地址
     * @return
     */
    private  Request getRequest(String downloadUrl) {
        Request.Builder builder = new Request.Builder();
        builder.url(downloadUrl).tag(downloadUrl);
        return builder.build();
    }

    /**
     * 通过键值对(表单中的name-value)创建RequestBody
     *
     * @param map 由提交的表单的每一项组成的HashMap
     *            （如用户名，key:username,value:zhangsan）
     * @return
     */
    private  RequestBody getRequestBody(HashMap<String, String> map) {
        FormBody.Builder builder = new FormBody.Builder();
        for (HashMap.Entry<String, String> entry : map.entrySet()) {
            builder.add(entry.getKey(), entry.getValue());
        }
        return builder.build();
    }

    /**
     * 根据表单的键值对和上传的文件生成RequestBody
     *
     * @param map       由提交的表单的每一项组成的HashMap
     *                  （如用户名，key:username,value:zhangsan）
     * @param fileNames 完整的文件路径名
     * @return
     */
    private  RequestBody getRequestBody(HashMap<String, String> map, List<String> fileNames) {
        MultipartBody.Builder builder = new MultipartBody.Builder(); //创建MultipartBody.Builder，用于添加请求的数据
        for (HashMap.Entry<String, String> entry : map.entrySet()) { //对键值对进行遍历
            builder.addFormDataPart(entry.getKey(), entry.getValue()); //把键值对添加到Builder中
        }
        for (int i = 0; i < fileNames.size(); i++) { //对文件进行遍历
            File file = new File(fileNames.get(i)); //生成文件
            String fileType = getMimeType(file.getName()); //根据文件的后缀名，获得文件类型
            builder.addFormDataPart( //给Builder添加上传的文件
                    "image",  //请求的名字
                    file.getName(), //文件的文字，服务器端用来解析的
                    RequestBody.create(MediaType.parse(fileType), file) //创建RequestBody，把上传的文件放入
            );
        }
        return builder.build(); //根据Builder创建请求
    }


    /**
     * 通过上传的文件的完整路径生成RequestBody
     *
     * @param fileNames 完整的文件路径
     * @return
     */
    private  RequestBody getRequestBody(List<String> fileNames) {
        //创建MultipartBody.Builder，用于添加请求的数据
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        for (int i = 0; i < fileNames.size(); i++) { //对文件进行遍历
            File file = new File(fileNames.get(i)); //生成文件
            //根据文件的后缀名，获得文件类型
            String fileType = getMimeType(file.getName());
            builder.addFormDataPart( //给Builder添加上传的文件
                    "File[]",  //请求的名字
                    file.getName(), //文件的文字，服务器端用来解析的
                    RequestBody.create(MediaType.parse(fileType), file) //创建RequestBody，把上传的文件放入
            );
        }
        return builder.build(); //根据Builder创建请求
    }

    /**
     * 只上传文件
     * 根据url，发送异步Post请求(带进度)
     *
     * @param url                       提交到服务器的地址
     * @param fileNames                 完整的上传的文件的路径名
     * @param uiProgressRequestListener 上传进度的监听器
     * @param callback                  OkHttp的回调接口
     */
    public  void uploadFile(String url, List<String> fileNames, ProgressListener uiProgressRequestListener, Callback callback) {
        Call call = client.newCall(getRequest(url, fileNames, uiProgressRequestListener));
        call.enqueue(callback);
    }

    /**
     * 只上传文件
     * 根据url，发送异步Post请求(不带进度)
     *
     * @param url       提交到服务器的地址
     * @param fileNames 完整的上传的文件的路径名
     * @param callback  OkHttp的回调接口
     */
    public  void uploadFile(String url, List<String> fileNames, Callback callback) {
        Call call = client.newCall(getRequest(url, fileNames));
        call.enqueue(callback);
    }

    /**
     * 只提交表单
     * 根据url和键值对，发送异步Post请求
     *
     * @param url      提交到服务器的地址
     * @param map      提交的表单的每一项组成的HashMap
     *                 （如用户名，key:username,value:zhangsan）
     * @param callback OkHttp的回调接口
     */
    public  void doAsyPost(String url, HashMap<String, String> map, Callback callback) {
        Call call = client.newCall(getRequest(url, map));
        call.enqueue(callback);
    }
    /**
     * 只提交表单
     * 根据url和键值对，发送异步Post请求
     *
     * @param url      提交到服务器的地址
     * @param map      提交的表单的每一项组成的HashMap
     *                 （如用户名，key:username,value:zhangsan）
     */
    public  String doPost(String url, HashMap<String, String> map) {
        Call call = client.newCall(getRequest(url, map));
        Response execute = null;
        String resData = "";
        try {
              execute = call.execute();
        } catch (IOException e) {
            resData = "";
        }
        if(null != execute ){
            try {
                resData = execute.body().string();
            } catch (IOException e) {
                resData = "";
            }
        }
        return resData;
    }

    /**
     * 可同时提交表单，和多文件
     * 根据url和键值对，发送异步Post请求
     *
     * @param url       提交到服务器的地址
     * @param map       提交的表单的每一项组成的HashMap
     *                  （如用户名，key:username,value:zhangsan）
     * @param fileNames 完整的上传的文件的路径名
     * @param callback  OkHttp的回调接口
     */
    public  void doMutilPost(String url, HashMap<String, String> map, List<String> fileNames, Callback callback) {
        Call call = client.newCall(getRequest(url, map, fileNames));
        call.enqueue(callback);
    }








}
